'use strict'

import React, { Component } from 'react';
import {
    View,
    Image,
    StyleSheet,
    TouchableOpacity,
    Dimensions
} from 'react-native';
import PropTypes from "prop-types";

import Color from '../../config/theme/standard/color';
import Label from "../label";


export default class Radio extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            is_active_index: props.initial,
            isWideScreen: false // 鸿蒙适配是否宽屏
        }
        this._renderButton = this._renderButton.bind(this);

    }

    componentDidMount() {
        // 适配鸿蒙折叠屏动态更新组件
        this.addEventListenerScreenWidth = Dimensions.addEventListener('change', this.setIsWideScreen)
    }
    componentWillUnmount() {
        // 适配鸿蒙折叠屏动态更新组件
        if (this.addEventListenerScreenWidth) {
            this.addEventListenerScreenWidth = null
        }
    }
    setIsWideScreen = () => {
        const screenWidth = Dimensions.get('window').width;
        if (screenWidth) {
            this.setState({
                isWideScreen: screenWidth > 500 && screenWidth < 800
            })
        }
    }


    static defaultProps = {
        radio_props: [],
        initial: 0,
        isToggle:true,
        buttonColor: Color.main,
        selectedButtonColor: Color.main,
        imgSelected: require('../../assets/radio_enabled.png'),
        imgDisabled: require('../../assets/radio_disabled.png'),
        formHorizontal: false,
        labelBefore: false,
        disabled: false,
        isMerge: false,
        formStyle: null,
    };

    _renderButton(obj, i) {
        return (
            <RadioButton
                isSelected={this.state.is_active_index === i}
                obj={obj}
                key={i}
                index={i}
                buttonColor={this.state.is_active_index === i ? this.props.selectedButtonColor : this.props.buttonColor}
                formHorizontal={this.props.formHorizontal}
                labelBefore={this.props.labelBefore}
                disabled={this.props.disabled}
                imgSelected={this.props.imgSelected}
                imgDisabled={this.props.imgDisabled}
                imgStyles={this.props.imgStyles}
                onPress={(index) => {
                    if(this.state.is_active_index === index && this.props.isToggle){
                        this.props.onPress(-1);
                        this.setState({is_active_index: -1})
                    }  else {
                        this.props.onPress(index);
                        this.setState({is_active_index: index})
                    }
                }}
                divider={(this.props.radio_props.length-1) == i ? Style.divider : Style.dividerMerge}
                isMerge={this.props.isMerge}//是否分组合并
                formStyle={this.props.formStyle}//整体自定义样式
                wrapStyle={this.props.wrapStyle}//每一项自定义样式
            />
        )
    }

    render() {
        let render_content = false;
        if (this.props.radio_props.length) {
            render_content = this.props.radio_props.map(this._renderButton)
        } else {
            render_content = this.props.children
        }
        return (
            <View style={[this.props.formStyle, this.props.formHorizontal && Style.formHorizontal]}>
                {render_content}
            </View>
        )
    }
}

Radio.propTypes = {
    //radio数据
    radio_props: PropTypes.array,
    //默认选中项
    initial: PropTypes.number,
    // 文字标签位置，false样式1，按钮位于左侧，true样式2，按钮位于右侧
    labelBefore: PropTypes.bool,
    //样式1按钮颜色
    buttonColor: PropTypes.string,
    //样式1按钮选中颜色
    selectedButtonColor: PropTypes.string,
    //样式2选中图片
    imgSelected: PropTypes.any,
    //样式2不可用图片
    imgDisabled: PropTypes.any,
    //样式2图片自定义样式
    imgStyles: PropTypes.object,
    //单选按钮组是否横向排布
    formHorizontal: PropTypes.bool,
    //是否可用
    disabled: PropTypes.bool,
    //点击事件
    onPress: PropTypes.func,
    //是否分组合并样式（否/是）
    isMerge: PropTypes.bool,
    //整体自定义样式
    formStyle: PropTypes.any,
    //每一项自定义样式
    wrapStyle: PropTypes.any,
    //radio多次点击是否可以重置为未选中状态
    isToggle: PropTypes.bool
}

export class RadioButton extends React.Component {
    constructor(props) {
        super(props);
    }

    shouldComponentUpdate(nextProps, nextState) {
        return true
    }

    static defaultProps = {
        isSelected: false,
        buttonColor: Color.main,
        buttonDisabledColor: Color.icon.disable,
        formHorizontal: false,
        labelBefore: false,
        disabled: false,
    };

    render () {

        let divider = null;

        if (!this.props.formHorizontal) {
            if (this.props.isMerge) {
                divider = (
                    <View style={this.props.divider}/>
                )
            } else {
                divider = (
                    <View style={Style.divider}/>
                )
            }

        }
        let wrapStyle = [Style.radioWrap];
        
        let formHorizontalStyle = [Style.radioformHorizontalStyle];

        if(this.props.obj.desc){
            wrapStyle.push({height:67,paddingTop: 12})
        }

        if(this.props.labelBefore && !this.props.obj.desc){
            wrapStyle.push({alignItems: 'center'})
        }


        let renderContent1 = (
            <View style={wrapStyle}>
                <RadioButtonInput {...this.props}/>
                <RadioButtonLabel {...this.props}/>
            </View>
        );

        let renderContent2 = (
            <View style={wrapStyle}>
                <RadioButtonLabel {...this.props}/>
                <RadioButtonInput {...this.props}/>
            </View>
        );

        if(this.props.labelBefore){
            return (
                <TouchableOpacity activeOpacity={0.8}
                    onPress={() => {this.props.onPress(this.props.index)}}
                    disabled={this.props.disabled || this.props.obj.disabled}
                >
                    {renderContent2}
                    {divider}
                </TouchableOpacity>
            )
        } else {
            return (
                <TouchableOpacity activeOpacity={0.8}
                    onPress={() => {this.props.onPress(this.props.index)}}
                    disabled={this.props.disabled || this.props.obj.disabled}
                    style={this.props.formHorizontal ? [{maxWidth: Dimensions.get('window').width/2}, this.props.wrapStyle, formHorizontalStyle] : this.props.wrapStyle}
                >
                    {renderContent1}
                    {divider}
                </TouchableOpacity>
            )
        }
    }
}

export class RadioButtonInput extends React.Component {
    constructor (props) {
        super(props);
    }

    render () {

        let innerSize = {width: 14, height: 14, borderRadius: 14/2 };
        let outerSize = {width: 26, height: 26, borderRadius: 26/2 };

        let c = (
            <View style={[
                Style.radioNormal,
                this.props.isSelected && Style.radioActive,
                this.props.isSelected && innerSize,
                this.props.isSelected && {backgroundColor: this.props.buttonColor},
                (this.props.disabled || this.props.obj.disabled) && {backgroundColor: Color.icon.disable}
            ]}/>
        );

        let radioStyle = [ Style.radio, { borderColor: this.props.buttonColor, borderWidth: 1 }, outerSize ];
        let radioDisableStyle = [ Style.radio, { borderColor: Color.icon.disable, borderWidth: 1 }, outerSize];
        let imageStyle = [ Style.image ];
        if(!this.props.obj.desc){
            radioStyle.push({alignSelf: 'center'})
            radioDisableStyle.push({alignSelf: 'center'})
        }
        
        if(this.props.obj.desc){
            imageStyle.push({marginTop: 12})
        }
        if(this.props.imgStyles){
            imageStyle.push(this.props.imgStyles);
        }
        let image = null;

        if(this.props.isSelected && this.props.labelBefore && !(this.props.disabled || this.props.obj.disabled)){
            return (
                <Image style={imageStyle} source={this.props.imgSelected}/>
            )
        }

        if(this.props.isSelected && this.props.labelBefore && (this.props.disabled || this.props.obj.disabled)){
            return (
                <Image style={imageStyle} source={this.props.imgDisabled}/>
            )
        }

        if (this.props.labelBefore) {
            return (
                <TouchableOpacity activeOpacity={0.8}
                     onPress={() => { this.props.onPress(this.props.index)}}
                     disabled={this.props.disabled || this.props.obj.disabled}
                >
                    {image}
                </TouchableOpacity>
            )
        } else {
            return (
                <TouchableOpacity activeOpacity={0.8}
                    style={this.props.disabled || this.props.obj.disabled ? radioDisableStyle : radioStyle}
                    onPress={() => { this.props.onPress(this.props.index)}}
                    disabled={this.props.disabled || this.props.obj.disabled}
                >
                    {c}
                </TouchableOpacity>
            )
        }
    }
}

RadioButtonInput.defaultProps = {
    buttonInnerColor: Color.main,
    buttonOuterColor: Color.main,
    buttonDisabledColor: Color.icon.disable,
    disabled: false,
    labelBefore: false,
};

export class RadioButtonLabel extends React.Component {

    constructor (props) {
        super(props)
    }
  
    render () {
        let sWidth =Dimensions.get('window').width;
        let labelWrapStyle = [Style.labelWrapStyle];
        
        if (!this.props.formHorizontal) {
            labelWrapStyle.push({width: sWidth-49-15})
        }

        if (this.props.formHorizontal) {
            labelWrapStyle.push({width: 200})
        }

        if(!this.props.obj.desc){
            labelWrapStyle.push({justifyContent: 'center'})
        }

        let descColor = '#666';
        
        return (
            <TouchableOpacity activeOpacity={0.8} onPress={() => { if (!this.props.disabled) {this.props.onPress( this.props.index)}}} disabled={this.props.disabled || this.props.obj.disabled}>
                <View style={this.props.labelBefore ? [labelWrapStyle, {width: sWidth-49}] : labelWrapStyle} >
                    <Label labelStyle={this.props.labelBefore ? [Style.radioLabel, {paddingLeft: 12}] : Style.radioLabel} text={this.props.formHorizontal ? this.props.obj.label.slice(0, 7) : this.props.obj.label} numberOfLines={1} color={'normal'}/>
                    {this.props.obj.desc?
                        <Label labelStyle={this.props.labelBefore ? [Style.radioLabeldesc, {paddingLeft: 12,color:descColor}] : [Style.radioLabeldesc,{color:descColor}]} text={this.props.obj.desc} numberOfLines={1} />
                    :null}
                </View>
            </TouchableOpacity>
        )
    }
}

let Style = StyleSheet.create({
    radioFrom: {

    },

    radioWrap: {
        flexDirection: 'row',
        paddingTop: 0,
        height: 44,
    },

    radio: {
        justifyContent: 'center',
        alignItems: 'center',
        width: 26,
        height: 26,
        marginLeft: 15
    },

    labelWrapStyle: {
        flexDirection: 'column',
        alignItems: 'flex-start',
        alignSelf: 'center',
        height: 44,
    },

    radioLabel: {
        paddingLeft: 6,
        fontSize: 15,
    },

    radioLabeldesc: {
        paddingLeft: 6,
        fontSize: 12,
        color:'#666',
        marginTop: 5,
    },

    radioNormal: {
        borderRadius: 14
    },

    radioActive: {
        width: 24,
        height: 24,
        backgroundColor: Color.main,
    },

    formHorizontal: {
        flexDirection: 'row',
        flexWrap: 'wrap'
    },

    radioformHorizontalStyle: {
        minWidth: 100,
    },

    image: {
        width: 28,
        height: 28,
        position: 'absolute',
        right: 15,
        resizeMode:'contain'
    },

    divider :{
        width:Dimensions.get('window').width,
        height: 1,
        backgroundColor:Color.border,
    },

    dividerMerge: {
        width: Dimensions.get('window').width-12,
        height: 1,
        backgroundColor:Color.border,
        position: 'relative',
        left: 15,
    },
});

module.exports = Radio;
